<template>
	<!-- 
  支付页面
 -->
	<view class="pyg_buy">
		<!-- 收货地址开始 -->
		<view class="pyg_buy_address">
			<!-- 收货地址存在开始 -->
			<block v-if="address.all">
				<view class="address_all">地址：{{address.all}}</view>
				<view class="nameAndPhone">
					<text class="name">姓名：{{address.userName}}</text>
					<text class="telNumber">电话：{{address.telNumber}}</text>
				</view>
				<view class="chooseAnotherAddress" type="primary" size="10" plain @tap="handleAddressChange">重选
				</view>
			</block>
			<!-- 收货地址存在结束 -->
			<!-- 当地址不存在的时候 开始 -->
			<view class="empty_address" v-else>
				<!-- 
      使用微信wx.chooseAddress 调用系统自带的选择地址功能
     -->
				<view class="choose_address" @tap="handleAddressChoose">选择地址</view>
			</view>
			<!-- 当地址不存在的时候 结束-->
		</view>
		<!-- 收货地址结束 -->
		<!-- 已选商品列表开始 -->
		<view class="product_list">
			<!-- 标题开始 -->
			<view class="product_title">已选商品</view>
			<!-- 标题结束 -->
			<!-- 商品列表开始 
      1. 拿到购物小车数据
      2. 判断 => v.checked === true ==> 商品才被渲染出来
    -->
			<view class="product_list_item" v-for="(item,index) in carts" v-if="item.checked" :key="item.goods_id">
				<view class="image_wrapper">
					<!-- 
						  如果图片不存在的情况下 直接显示一张空白图片
						  https://ww1.sinaimg.cn/large/007rAy9hgy1g24by9t530j30i20i2glm.jpg
 			        -->
					<image
						:src="item.goods_small_logo?item.goods_small_logo:'https://ww1.sinaimg.cn/large/007rAy9hgy1g24by9t530j30i20i2glm.jpg'">
					</image>
				</view>
				<!-- 商品列表的介绍开始 -->
				<view class="desc">
					<view class="title">{{item.goods_name}}</view>
					<view class="priceAndNum">
						<view class="price">￥{{item.goods_price}}</view>
						<view class="num">x{{item.num}}</view>
					</view>
				</view>
				<!-- 商品列表的介绍结束 -->
			</view>
			<!-- 商品列表结束 -->
			<!-- 底部支付栏开始 -->
			<view class="pay_bottom">
				<view class="pay_left">
					<text class="text1">合计:</text>
					<text class="price1">￥{{totalPrice}}</text>
				</view>
				<!-- 当地址不为空 以及 totalNum不为0 的情况下，才能发起支付；否则不可以-->
				<view class="pay_right">
					<!-- if address.all&&totalNum  开始-->
					<view class="pay_button" v-if="address.all&&totalNum" @tap="handlePay">去支付({{totalNum}})
					</view>
					<!-- if {{address.all&&totalNum}}  结束-->
					<!--else 开始-->
					<view v-else class="pay_button_disable">去支付({{totalNum}})</view>
					<!--else 结束-->
				</view>
			</view>

			<!-- 底部支付栏结束 -->
		</view>

		<!-- 已选商品列表结束 -->

	</view>
</template>
<!-- // pages/pay/pay.js
/* 
handleAddressChoose 获取用户当前的收货地址
1. 直接选择地址就可以了 uni.chooseAdress
2. 拼接当前地址 用户收货地址  address.all =  provinceName cityName countyName detailInfo
3. 获取到的地址设置到缓存 storage 还有 data中

*******************************
handlePay 在本应用 微信支付流程
A. 环境的准备
   a.1 如果你是使用 https://106.55.254.112/api/public/v1/ 接口的同学
   appId = wx45f217ba2cb42557
   同时把你的微信号 给到 林老师 =》 微信后台添加到开发者账号 
   a.2 如果你是使用第三方平台提供的支付接口，就去平台看对应配置文档
  
B. 微信支付流程 
1. 获取 token => openID 唯一标识  
接口：https://www.showdoc.cc/128719739414963?page_id=2612400282844951
2. 在系统中创建一个订单 
接口 ：https://www.showdoc.cc/128719739414963?page_id=2612148628877795
3. 获取支付参数
接口：https://www.showdoc.cc/128719739414963?page_id=2612486239891213
4. 发起支付  uni.requestPayment
https://uniapp.dcloud.net.cn/api/plugins/payment?id=requestpayment
5. 查询是否支付成功
接口：https://www.showdoc.cc/128719739414963?page_id=2612723166377091
6. 把本地缓存中 carts 已经支付的商品 删除
7. 跳转到订单查询页面 /pages/order/order -->
<script>
	import {
		chooseAddress,
		requestPayment,
		showToast
	} from "@/utils/asyncWx.js"
	export default {
		onLoad: function(options) {
			//获取购物车小车商品内容 carts
			let carts = wx.getStorageSync("carts") || [];
			//获取当前选择的地址
			let address = wx.getStorageSync("address") || {};
			//通过 setCarts初始化购物小车数据
			this.setCarts(carts);
			this.address = address;
		},
		data() {
			return {
				//address.all => true 直接渲染收货地址
				//address.all => false 直接渲染 选择地址功能
				address: {}, //存收货信息 
				carts: [], //购物小车数据
				totalPrice: 0, //总价
				totalNum: 0 //总数量
			}
		},
		methods: {
			// 处理微信支付的流程
			handlePay: async function(e) {
				try {
					//1. 获取token => openID 用户的唯一标识
					let token = uni.getStorageSync("token");
					//如果本地缓存中没有token,此时我们就需要跳转去授权页面获取token
					if (!token) {
						wx.navigateTo({
							url: '/pages/auth/auth',
						})
						return;
					}
					//开始支付流程
					//2. 创建系统订单 
					//开始拼接创建订单需要的 请求参数
					let order_price = this.totalPrice;
					let consignee_addr = this.address.all;
					let goods = [];
					//获取goods 的参数列表
					this.carts.forEach(v => {
						//判断购物小车是否被选中
						if (v.checked) {
							let params = {};
							params["goods_id"] = v.goods_id;
							params["goods_number"] = v.num;
							params["goods_price"] = v.goods_price;
							goods.push(params);
						}
					})
					//订单的请求参数
					let order_params = {
						order_price: order_price,
						consignee_addr: consignee_addr,
						goods: goods
					}
					//创建订单
					const {
						order_number
					} = await this.$request({
						url: "/my/orders/create",
						method: "post",
						data: order_params
					});
					// console.log(order_number);
					//3. 获取支付参数
					const {
						pay
					} = await this.$request({
						url: "/my/orders/req_unifiedorder",
						method: "POST",
						data: {
							order_number
						}
					});
					//console.log(pay);
					// 4.发起支付 uni.requestPayment  https://uniapp.dcloud.net.cn/api/plugins/payment?id=requestpayment
					await requestPayment(pay);
					//5. 查询一下订单状态
					let res = await this.$request({
						url: "/my/orders/chkOrder",
						method: "post",
						data: {
							order_number
						}
					});
					//提示用户 支付成功
					await showToast({
						title: "支付成功"
					});
					//6 手动删除已经支付的商品信息
					let newCarts = uni.getStorageSync("carts") || [];
					//!v.checked 没有被选中支付的商品
					newCarts = newCarts.filter(v => !v.checked)
					//设置回本地缓存
					uni.setStorageSync("carts", newCarts);
					//7. 跳转到订单页面
					uni.navigateTo({
						url: '/pages/order/order',
					})

				} catch (e) {
					console.log(e);
					//提示用户 支付失败
					showToast({
						title: "支付失败"
					})
				}

			},
			//重新选择地址
			handleAddressChange: async function(e) {
				//捕捉各种获取权限过程中可能出现的异常
				try {
					//获取用户的地址 wx.chooseAddress
					let address = await chooseAddress();
					//拼接地址
					address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;
					//存到缓存和 this.data中
					uni.setStorageSync("address", address);
					this.address = address;
				} catch (e) {
					console.log(e);

				}
			},
			
			//1. 设置购物小车的值
			//2. 计算选中商品的价格
			//3 计算选中商品的数量
			setCarts: function(carts) {
				let totalNum = 0; //商品的数量
				let totalPrice = 0; //商品的价格
				// console.log(carts);
				//对购物小车做循环 找到 checked 为true 的项  把价格和数量相加
				carts.forEach(v => {
					if (v.checked) {
						totalNum += v.num; //商品数量总和
						totalPrice += v.num * v.goods_price;
					}
				})
				this.carts = carts;
				this.totalNum = totalNum;
				this.totalPrice = totalPrice;
			},
			// 获取用户的收货地址
			// uni.chooseAddress 接口
			handleAddressChoose: async function(e) {
				//捕捉各种获取权限过程中可能出现的异常
				try {
	
					//获取用户的地址 wx.chooseAddress
					let address = await chooseAddress();
					//拼接地址
					address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;
					//存到缓存和 this.data中
					wx.setStorageSync("address", address);
					
					this.address = address;
			
				} catch (e) {
					console.log(e);

				}
			},
			//作用 
			//1. 设置购物小车的值
			//2. 计算选中商品的价格
			//3 计算选中商品的数量
			setCarts: function(carts) {
				let totalNum = 0; //商品的数量
				let totalPrice = 0; //商品的价格
				//对购物小车做循环 找到 checked 为true 的项  把价格和数量相加
				carts.forEach(v => {
					if (v.checked) {
						totalNum += v.num; //商品数量总和
						totalPrice += v.num * v.goods_price;
					}
				})
				this.carts = carts;
				this.totalNum = totalNum;
				this.totalPrice = totalPrice;
			},
		}
	}
</script>

<style lang="less">
	.pyg_buy {
		/* 地址 */
		/* 商品列表 */
		/* 底部工具栏 */
	}

	.pyg_buy .pyg_buy_address {
		background-color: #fff;
		width: 720rpx;
		height: 187rpx;
		margin: 21rpx 19rxp 35rpx 29rpx;
		display: flex;
		justify-content: space-around;
		flex-direction: column;
		/* 地址 */
		/*空白地址 */
	}

	.pyg_buy .pyg_buy_address .address_all {
		font-size: 30rpx;
		color: #434343;
		margin: 16rpx 17rpx 18rpx 29rpx;
	}

	.pyg_buy .pyg_buy_address .nameAndPhone {
		margin-left: 29rpx;
		font: size 26rpx;
		color: #434343;
	}

	.pyg_buy .pyg_buy_address .nameAndPhone text.name {
		margin-right: 19rpx;
	}

	.pyg_buy .pyg_buy_address .chooseAnotherAddress {
		margin-top: 10rpx;
		margin-left: 29rpx;
		color: var(--themeColor);
	}

	.pyg_buy .pyg_buy_address .empty_address {
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.pyg_buy .pyg_buy_address .empty_address .choose_address {
		width: 303rpx;
		height: 89rpx;
		border-radius: 45rpx;
		border: 2rpx solid #EA4350;
		color: #EA4350;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.pyg_buy .product_list {
		margin: 0 32rpx 0 20rpx;
	}

	.pyg_buy .product_list .product_title {
		font-size: 26rpx;
		color: #434343;
		margin: 17rpx 0 17rpx 26rpx;
		font-weight: 500;
	}

	.pyg_buy .product_list .product_list_item {
		height: 209rpx;
		width: 698rpx;
		overflow: hidden;
		background-color: white;
	}

	.pyg_buy .product_list .product_list_item .image_wrapper {
		float: left;
		margin: 9rpx 29rpx 9rpx 15rpx;
	}

	.pyg_buy .product_list .product_list_item .image_wrapper image {
		height: 191rpx;
		width: 191rpx;
	}

	.pyg_buy .product_list .product_list_item .desc {
		height: 156rpx;
		margin-top: 26rpx;
		margin-bottom: 27rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.pyg_buy .product_list .product_list_item .desc .title {
		font-size: 24rpx;
		color: #434343;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		overflow: hidden;
		-webkit-line-clamp: 2;
	}

	.pyg_buy .product_list .product_list_item .desc .priceAndNum {
		display: flex;
		justify-content: space-between;
	}

	.pyg_buy .product_list .product_list_item .desc .priceAndNum .price {
		font-size: 24rpx;
		color: var(--themeColor);
	}

	.pyg_buy .product_list .product_list_item .desc .priceAndNum .num {
		font-size: 28rpx;
		color: #434343;
		margin-right: 13rpx;
	}

	.pyg_buy .pay_bottom {
		position: fixed;
		left: 0;
		bottom: 0;
		height: 83rpx;
		width: 100vw;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: white;
	}

	.pyg_buy .pay_bottom .pay_left .text1 {
		font-size: 26rpx;
		color: #292929;
		margin-left: 29rpx;
	}

	.pyg_buy .pay_bottom .pay_left .price1 {
		font-size: 28rpx;
		color: #EA4350;
	}

	.pyg_buy .pay_bottom .pay_right {
		/* 支付按钮 */
	}

	.pyg_buy .pay_bottom .pay_right .pay_button {
		width: 150rpx;
		height: 52rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: var(--themeColor);
		border-radius: 26rpx;
		color: white;
		font-size: 21rpx;
		margin-right: 27rpx;
	}

	.pyg_buy .pay_bottom .pay_right .pay_button_disable {
		width: 150rpx;
		height: 52rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #B6B6B6;
		border-radius: 26rpx;
		color: white;
		font-size: 21rpx;
		margin-right: 27rpx;
	}
</style>
